package com.nageoffer.aicloud.service.Impl;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.nageoffer.aicloud.dto.resp.CaptchaRespDTO;
import com.nageoffer.aicloud.service.CaptchaService;
import com.nageoffer.aicloud.utils.MinioConfig;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import static com.nageoffer.aicloud.common.content.RedisKeyContent.CAPTCHA_KEY;

/**
 * 图片验证码接口实现层
 */
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {
    private final MinioConfig minioConfig;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public CaptchaRespDTO createCaptCha(HttpServletRequest request) throws Exception {
        //定义图形验证码的长和宽
        CaptchaRespDTO captcha = CaptchaRespDTO.builder().build();
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        String fileName = "Captcha-" + SecureUtil.md5(request.getRemoteAddr());
        try (InputStream stream = new ByteArrayInputStream(lineCaptcha.getImageBytes())) {
            captcha.setImageUrl(minioConfig.uploadFile(fileName, stream, "image/png"));
            // 将验证码信息存储到 Redis中
            stringRedisTemplate.opsForValue().set(CAPTCHA_KEY + fileName, lineCaptcha.getCode(), 60, TimeUnit.SECONDS);
        }
        return captcha;
    }
}
